package tq.com.tqstudent.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;

import com.igexin.sdk.PushManager;
import com.lib.common.base.BaseActivity;
import com.lib.common.utils.AppManager;
import com.lib.common.utils.LogUtil;
import com.lib.common.utils.SPUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import tq.com.tqstudent.Constants;
import tq.com.tqstudent.R;
import tq.com.tqstudent.bean.HomeTabs;
import tq.com.tqstudent.bean.event.LoginOutEvent;
import tq.com.tqstudent.bean.event.SwitchEvent;
import tq.com.tqstudent.push.GTPushIntentService;
import tq.com.tqstudent.push.GTPushService;
import tq.com.tqstudent.ui.fragment.ClassFragment;
import tq.com.tqstudent.views.TabFragmentHost;

/**
 * @Author rames
 * @date 2019/2/27 11:05
 */
public class HomeActivity extends BaseActivity implements TabHost.OnTabChangeListener {
    private TabFragmentHost tabHost;
    private TextView titleTV;

    public static void show(Activity activity) {
        activity.startActivity(new Intent(activity, HomeActivity.class));
    }

    @Override
    public int initLayout() {
        return R.layout.activity_home;
    }

    @Override
    protected boolean setAdaptNotchBar() {
        return false;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        SPUtils.getInstance(this).putBoolean(Constants.IS_CHAT_ACTIVITY_PUSH, false);
        tabHost = super.findViewById(android.R.id.tabhost);
        tabHost.setup(this, super.getSupportFragmentManager(), R.id.contentLayout);
        tabHost.getTabWidget().setDividerDrawable(null);
        tabHost.setOnTabChangedListener(this);

        getTitleView().getBackImg().setVisibility(View.INVISIBLE);
        titleTV = getTitleView().getTitleTV();
        initTab();
    }

    private void initTab() {
        String tabs[] = HomeTabs.getTabsText();
        for (int i = 0; i < tabs.length; i++) {
            TabHost.TabSpec tabSpec = tabHost.newTabSpec(tabs[i]).setIndicator(getTabView(i));
            tabHost.addTab(tabSpec, HomeTabs.getFragments()[i], null);
            tabHost.setTag(i+"");
        }
    }

    private View getTabView(int idx) {
        View view = LayoutInflater.from(this).inflate(R.layout.tabs_activity_home, null);
        ((TextView) view.findViewById(R.id.tvTab)).setText(HomeTabs.getTabsText()[idx]);
        if (idx == 0) {
            ((TextView) view.findViewById(R.id.tvTab)).setTextColor(getResources().getColor(R.color.color_028AE1));
            ((ImageView) view.findViewById(R.id.ivImg)).setImageResource(HomeTabs.getTabsImgLight()[idx]);
        } else {
            ((ImageView) view.findViewById(R.id.ivImg)).setImageResource(HomeTabs.getTabsImg()[idx]);
        }
        return view;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        getDelegate().onSaveInstanceState(outState);
    }

    @Override
    public void initData() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE);

                // 有权限
            } else {
                PushManager.getInstance().initialize(getApplicationContext(), GTPushService.class);
                PushManager.getInstance().registerPushIntentService(getApplicationContext(), GTPushIntentService.class);
            }
        }
    }

    private final static int REQUEST_WRITE = 0x23;
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_WRITE && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            PushManager.getInstance().initialize(getApplicationContext(), GTPushService.class);
        }
    }

    private void getCid() {
        String cid = PushManager.getInstance().getClientid(this);
        if(cid != null && cid.length() > 0) {
            SPUtils.getInstance(this).putString(Constants.GT_PUSH_CID_KEY, cid);
        }
    }

    @Subscribe
    public void onEvent(String event) {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LoginOutEvent event){
        tabHost.setCurrentTab(0);
        String tag= tabHost.getCurrentTabTag();
        ClassFragment classFragment = (ClassFragment) getSupportFragmentManager().findFragmentByTag(tag);
        classFragment.refresh();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSwitchEvent(SwitchEvent event){
        LogUtil.e("onSwitchEvent-------");
        tabHost.setCurrentTab(0);
        String tag= tabHost.getCurrentTabTag();
        ClassFragment classFragment = (ClassFragment) getSupportFragmentManager().findFragmentByTag(tag);
        classFragment.refresh();
    }

    @Override
    public void onTabChanged(String s) {
        updateTab(tabHost.getCurrentTab());
    }

    private void updateTab(int index) {
        getCid();
        TabWidget tabw = tabHost.getTabWidget();
        for (int i = 0; i < tabw.getChildCount(); i++) {
            View view = tabw.getChildAt(i);
            ImageView iv = view.findViewById(R.id.ivImg);
            if (i == index) {
                titleTV.setText(HomeTabs.getTabsText()[i]);
                ((TextView) view.findViewById(R.id.tvTab)).setTextColor(getResources().getColor(R.color.color_028AE1));
                iv.setImageResource(HomeTabs.getTabsImgLight()[i]);
            } else {
                ((TextView) view.findViewById(R.id.tvTab)).setTextColor(getResources().getColor(R.color.color_999999));
                iv.setImageResource(HomeTabs.getTabsImg()[i]);
            }
        }
    }

//    // 用来计算返回键的点击间隔时间
//    private long exitTime = 0;
//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
//            if ((System.currentTimeMillis() - exitTime) > 2000) {
//                //弹出提示，可以有多种方式
//                showToast("再按一次退出程序");
//                exitTime = System.currentTimeMillis();
//            } else {
//                finish();
//                AppManager.getAppManager().AppExit(this);
//            }
//            return true;
//        }
//
//        return super.onKeyDown(keyCode, event);
//    }
}
